<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <div class="cart-stats">
        <el-tag type="info">共 {{ cartItems.length }} 件商品</el-tag>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车还是空的" :image-size="200">
        <template #description>
          <p>快去挑选心仪的商品吧！</p>
        </template>
        <el-button type="primary" @click="$router.push('/products')" size="large">
          <el-icon><ShoppingCart /></el-icon>
          去购物
        </el-button>
      </el-empty>
    </div>
    
    <div v-else class="cart-content">
      <!-- 购物车商品列表 -->
      <div class="cart-items">
        <div 
          v-for="item in cartItems" 
          :key="item.id" 
          class="cart-item"
        >
          <div class="item-image">
            <img 
              :src="item.product?.image || '/default-product.jpg'" 
              :alt="item.product?.name"
              @click="viewProduct(item.product?.id)"
            />
          </div>
          
          <div class="item-info">
            <h3 class="item-name" @click="viewProduct(item.product?.id)">
              {{ item.product?.name }}
            </h3>
            <p class="item-category">{{ item.product?.category }}</p>
          </div>
          
          <div class="item-price">
            <span class="price-label">单价：</span>
            <span class="price-value">¥{{ item.product?.price }}</span>
          </div>
          
          <div class="item-quantity">
            <el-input-number 
              v-model="item.quantity" 
              :min="1" 
              :max="item.product?.stock || 999"
              @change="(value) => updateQuantity(item.id, value)"
              size="small"
              :loading="item.updating"
            />
            <span class="stock-info">库存: {{ item.product?.stock || 0 }}</span>
          </div>
          
          <div class="item-subtotal">
            <span class="subtotal-label">小计：</span>
            <span class="subtotal-value">¥{{ (item.product?.price * item.quantity).toFixed(2) }}</span>
          </div>
          
          <div class="item-actions">
            <el-button 
              type="danger" 
              size="small" 
              @click="removeFromCart(item.id)"
              :loading="item.removing"
            >
              <el-icon><IconDelete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 购物车底部 -->
      <div class="cart-footer">
        <div class="footer-left">
          <el-button 
            type="danger" 
            size="small" 
            @click="clearCart" 
            :loading="clearing"
            v-if="cartItems.length > 0"
          >
            <el-icon><IconDelete /></el-icon>
            清空购物车
          </el-button>
        </div>
        
        <div class="footer-right">
          <div class="total-info">
            <p>商品总数：{{ totalQuantity }} 件</p>
            <p class="total-price">总计：¥{{ totalPrice.toFixed(2) }}</p>
          </div>
          <div class="checkout-actions">
            <el-button 
              type="primary" 
              size="large" 
              @click="checkout" 
              :loading="checkingOut"
              :disabled="cartItems.length === 0"
            >
              <el-icon><ShoppingCart /></el-icon>
              结算 ({{ cartItems.length }})
            </el-button>
            <el-button 
              v-if="cartItems.length > 0"
              type="success" 
              size="large" 
              @click="testCheckout" 
              style="margin-left: 10px;"
            >
              测试完整结算流程
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单确认对话框 -->
    <OrderConfirmDialog
      v-model="showOrderConfirm"
      :cart-items="cartItems"
      :address="defaultAddress"
      @order-created="handleOrderCreated"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ShoppingCart } from '@element-plus/icons-vue';
import { IconDelete } from '@element-plus/icons-vue';
import OrderConfirmDialog from '@/components/OrderConfirmDialog.vue';

export default {
  name: 'CartPage',
  components: {
    ShoppingCart,
    IconDelete,
    OrderConfirmDialog
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();
    
    const cartItems = ref([]);
    const loading = ref(false);
    const clearing = ref(false);
    const checkingOut = ref(false);
    const showOrderConfirm = ref(false);
    const defaultAddress = ref(null);

    // 计算属性
    const totalQuantity = computed(() => {
      return cartItems.value.reduce((sum, item) => sum + item.quantity, 0);
    });

    const totalPrice = computed(() => {
      return cartItems.value.reduce((sum, item) => {
        return sum + (item.product?.price * item.quantity);
      }, 0);
    });

    const fetchCartItems = async () => {
      if (!userStore.isAuthenticated()) {
        router.push('/login');
        return;
      }

      loading.value = true;
      try {
        const response = await request.get('/cart', { params: { userId: userStore.userId } });
        
        if (response.code === 200) {
          cartItems.value = (response.data || []).map(item => ({
            ...item,
            updating: false,
            removing: false
          }));
        } else {
          ElMessage.error(response.message || '获取购物车失败');
        }
      } catch (error) {
        console.error('获取购物车失败:', error);
        ElMessage.error('获取购物车失败');
      } finally {
        loading.value = false;
      }
    };

    const updateQuantity = async (itemId, quantity) => {
      const item = cartItems.value.find(i => i.id === itemId);
      if (!item) return;

      item.updating = true;
      try {
        const response = await request.put(`/cart/items/${itemId}`, null, {
          params: { quantity, userId: userStore.userId }
        });
        
        if (response.code === 200) {
          ElMessage.success('数量更新成功');
        } else {
          ElMessage.error(response.message || '更新失败');
          fetchCartItems();
        }
      } catch (error) {
        ElMessage.error('更新失败: ' + (error.response?.data?.message || '网络错误'));
        fetchCartItems();
      } finally {
        item.updating = false;
      }
    };

    const removeFromCart = async (itemId) => {
      const item = cartItems.value.find(i => i.id === itemId);
      if (!item) return;

      try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        item.removing = true;
        const response = await request.delete(`/cart/items/${itemId}`, { params: { userId: userStore.userId } });
        
        if (response.code === 200) {
          ElMessage.success('删除成功');
          fetchCartItems();
        } else {
          ElMessage.error(response.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败: ' + (error.response?.data?.message || '网络错误'));
        }
      } finally {
        item.removing = false;
      }
    };

    const clearCart = async () => {
      if (cartItems.value.length === 0) {
        ElMessage.warning('购物车已经是空的');
        return;
      }

      try {
        await ElMessageBox.confirm('确定要清空购物车吗？此操作不可恢复！', '清空购物车', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        clearing.value = true;
        const response = await request.delete('/cart', { params: { userId: userStore.userId } });
        
        if (response.code === 200) {
          ElMessage.success('购物车已清空');
          cartItems.value = [];
        } else {
          ElMessage.error(response.message || '清空失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('清空失败: ' + (error.response?.data?.message || '网络错误'));
        }
      } finally {
        clearing.value = false;
      }
    };

    const checkout = async () => {
      if (cartItems.value.length === 0) {
        ElMessage.warning('购物车是空的');
        return;
      }

      checkingOut.value = true;
      try {
        // 获取用户默认地址
        let addressId = null;
        try {
          const addressResponse = await request.get('/address/default', { params: { userId: userStore.userId } });
          if (addressResponse.code === 200 && addressResponse.data) {
            addressId = addressResponse.data.id;
          }
        } catch (error) {
          // 如果获取地址失败，继续创建默认地址
          console.log('获取默认地址失败，将创建新地址');
        }

        // 如果没有地址，则自动创建默认地址
        if (!addressId) {
          const defaultAddress = {
            receiverName: '收货人',
            phone: '13800138000',
            province: '辽宁省',
            city: '大连市',
            district: '',
            detailAddress: '大连民族大学',
            userId: userStore.userId
          };
          const createRes = await request.post('/address', defaultAddress);
          if (createRes.code === 200) {
            addressId = createRes.data.id;
          } else {
            ElMessage.error('创建默认地址失败: ' + (createRes.message || '未知错误'));
            return;
          }
        }

        // 创建订单
        const cartItemIds = cartItems.value.map(item => parseInt(item.id));
        const orderResponse = await request.post('/orders', cartItemIds, {
          params: {
            userId: userStore.userId,
            addressId: addressId
          }
        });

        if (orderResponse.code === 200) {
          ElMessage.success('订单创建成功，正在跳转到支付页面...');
          setTimeout(() => {
            router.push(`/payment/${orderResponse.data.id}`);
          }, 1000);
        } else {
          ElMessage.error(orderResponse.message || '创建订单失败');
        }
      } catch (error) {
        console.error('结算错误:', error);
        ElMessage.error('结算失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        checkingOut.value = false;
      }
    };

    const handleOrderCreated = (orderData) => {
      // 订单创建成功后的处理
      ElMessage.success('订单创建成功，正在跳转到支付页面...');
      setTimeout(() => {
        router.push(`/payment/${orderData.id}`);
      }, 1500);
    };

    const viewProduct = (productId) => {
      if (productId) {
        router.push(`/product/${productId}`);
      }
    };

    const testCheckout = async () => {
      if (cartItems.value.length === 0) {
        ElMessage.warning('购物车是空的');
        return;
      }

      checkingOut.value = true;
      try {
        // 创建测试地址
        const testAddress = {
          receiverName: '测试用户',
          phone: '13800138000',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          detailAddress: '测试街道123号',
          userId: userStore.userId
        };

        // 先保存测试地址
        const addressResponse = await request.post('/address', testAddress);
        if (addressResponse.code !== 200) {
          ElMessage.error('创建测试地址失败');
          return;
        }

        const addressId = addressResponse.data.id;

        // 创建订单
        const cartItemIds = cartItems.value.map(item => parseInt(item.id));
        
        console.log('测试订单创建参数:', {
          userId: userStore.userId,
          addressId: addressId,
          cartItemIds: cartItemIds
        });
        
        const orderResponse = await request.post('/orders', cartItemIds, {
          params: { 
            userId: userStore.userId,
            addressId: addressId
          }
        });

        if (orderResponse.code === 200) {
          ElMessage.success('测试订单创建成功，正在跳转到支付页面...');
          setTimeout(() => {
            router.push(`/payment/${orderResponse.data.id}`);
          }, 1500);
        } else {
          ElMessage.error(orderResponse.message || '创建测试订单失败');
        }
      } catch (error) {
        ElMessage.error('测试结算失败: ' + (error.response?.data?.message || '网络错误'));
      } finally {
        checkingOut.value = false;
      }
    };

    onMounted(() => {
      fetchCartItems();
    });

    return {
      cartItems,
      loading,
      clearing,
      checkingOut,
      showOrderConfirm,
      defaultAddress,
      totalQuantity,
      totalPrice,
      fetchCartItems,
      updateQuantity,
      removeFromCart,
      clearCart,
      checkout,
      handleOrderCreated,
      viewProduct,
      testCheckout
    };
  }
};
</script>

<style scoped>
.cart-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.cart-header h2 {
  color: #303133;
  margin: 0;
}

.loading-container {
  padding: 40px;
}

.empty-cart {
  text-align: center;
  padding: 60px 20px;
}

.cart-content {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cart-items {
  padding: 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
  cursor: pointer;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.item-info {
  flex: 1;
  margin-right: 20px;
}

.item-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  cursor: pointer;
}

.item-name:hover {
  color: #409eff;
}

.item-category {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.item-price {
  width: 120px;
  margin-right: 20px;
  text-align: center;
}

.price-label {
  font-size: 12px;
  color: #909399;
}

.price-value {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.item-quantity {
  width: 150px;
  margin-right: 20px;
  text-align: center;
}

.stock-info {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.item-subtotal {
  width: 120px;
  margin-right: 20px;
  text-align: center;
}

.subtotal-label {
  font-size: 12px;
  color: #909399;
}

.subtotal-value {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.item-actions {
  width: 100px;
  text-align: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-info {
  text-align: right;
}

.total-info p {
  margin: 5px 0;
  color: #606266;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.checkout-actions {
  display: flex;
  gap: 10px;
}
</style>